﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using Newtonsoft.Json.Linq;

using Utils;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class UtilsServiceExtensions
    {
        private static Timer Timer;

        public static IServiceCollection AddAutoGC(this IServiceCollection services, TimeSpan period)
        {
            Timer = new Timer(Callback, null, period, period);
            return services;
        }

        public static IServiceCollection AddSecretOptions(this IServiceCollection services, IConfiguration configuration)
        {
            foreach (var item in configuration.GetChildren())
            {
                services.AddOptions<SecretOptions>(item.Key)
                    .Configure(options =>
                    {
                        Dictionary<string, object> dict = new Dictionary<string, object>();
                        item.Bind(dict);
                        if (options.ExtData == null)
                        {
                            options.ExtData = new JObject();
                        }
                        foreach (var children in dict)
                        {
                            if (children.Key.Contains("appId", StringComparison.OrdinalIgnoreCase))
                            {
                                options.AppId = children.Value?.ToString();

                            }
                            else if (children.Key.Contains("appSecret", StringComparison.OrdinalIgnoreCase))
                            {
                                options.AppSecret = children.Value?.ToString();
                            }
                            else
                            {
                                options.ExtData.Add(children.Key, JToken.FromObject(children.Value));
                            }
                        }
                    })
                    .Validate(a => new string[] { a.AppId, a.AppSecret }.All(b => !string.IsNullOrEmpty(b)), $"缺少{item.Key} 配置");
            }
            return services;
        }

        public static void Callback(object obj)
        {
            GC.Collect();
        }

    }
}
